package org.oc.qaq.service.Impl;

import org.oc.qaq.constant.MessageConstant;
import org.oc.qaq.entity.JwtUserDetails;
import org.oc.qaq.entity.Role;
import org.oc.qaq.entity.User;
import org.oc.qaq.mapper.UserMapper;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class MyUserDetailService implements UserDetailsService {
    private final UserMapper userMapper;

    public MyUserDetailService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOneByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(MessageConstant.LOGIN_ERROR);
        }
        Set<Role> roles = userMapper.findRolesByUsername(username);
        List<SimpleGrantedAuthority> authorities = roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
                .toList();

        return new JwtUserDetails(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                authorities
        );
    }
}
